﻿#include "user-Cart.h"

UserCart::UserCart(database &db, QWidget *parent)
    : QObject(parent), db(db), deliveryFee(0.0), businessId(-1)
{
}

UserCart::~UserCart()
{
}

void UserCart::clear()
{
    items.clear();
    emit cartChanged();
}

void UserCart::setBusinessInfo(int businessId, double deliveryFee)
{
    this->businessId = businessId;
    this->deliveryFee = deliveryFee;
    emit cartChanged();
}

void UserCart::updateQuantity(int productId, const QString &productName, double price, int delta)
{
    // 如果商品不在购物车中且尝试减少数量，直接返回
    if (!items.contains(productId) && delta < 0) {
        return;
    }

    // 如果商品不在购物车中且尝试增加数量，添加商品
    if (!items.contains(productId) && delta > 0) {
        CartItem item;
        item.productId = productId;
        item.productName = productName;
        item.price = price;
        item.quantity = 0;
        items.insert(productId, item);
    }

    // 更新商品数量
    CartItem &item = items[productId];
    item.quantity += delta;

    // 如果数量为0或负数，从购物车中移除
    if (item.quantity <= 0) {
        items.remove(productId);
    }

    // 发送购物车变化信号
    emit cartChanged();
}

int UserCart::getQuantity(int productId) const
{
    if (items.contains(productId)) {
        return items[productId].quantity;
    }
    return 0;
}

int UserCart::getTotalItems() const
{
    int total = 0;
    for (const CartItem &item : items.values()) {
        total += item.quantity;
    }
    return total;
}

double UserCart::getSubtotal() const
{
    double subtotal = 0.0;
    for (const CartItem &item : items.values()) {
        subtotal += item.price * item.quantity;
    }
    return subtotal;
}

double UserCart::getDeliveryFee() const
{
    return deliveryFee;
}

double UserCart::getTotalAmount() const
{
    return getSubtotal() + deliveryFee;
}

QMap<int, UserCart::CartItem> UserCart::getItems() const
{
    return items;
}

bool UserCart::isEmpty() const
{
    return items.isEmpty();
}

// CartWidget 实现
CartWidget::CartWidget(UserCart *cart, QWidget *parent)
    : QWidget(parent), cart(cart)
{
    // 创建布局
    QHBoxLayout *layout = new QHBoxLayout(this);

    // 总金额标签
    totalLabel = new QLabel("总金额: 0.00 元 (含配送费: 0.00 元)", this);
    totalLabel->setStyleSheet("font-size: 14pt; font-weight: bold;");

    // 确认购买按钮
    checkoutButton = new QPushButton("确认购买", this);
    checkoutButton->setFont(QFont("", 12, QFont::Bold));
    checkoutButton->setMinimumHeight(40);
    checkoutButton->setMinimumWidth(150);
    checkoutButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   border-radius: 5px;"
        "}"
        "QPushButton:disabled {"
        "   background-color: #cccccc;"
        "   color: #666666;"
        "}"
    );
    checkoutButton->setEnabled(false); // 初始状态禁用

    // 连接信号槽
    connect(cart, &UserCart::cartChanged, this, &CartWidget::onCartChanged);
    connect(checkoutButton, &QPushButton::clicked, this, &CartWidget::onCheckoutClicked);

    // 添加到布局
    layout->addWidget(totalLabel);
    layout->addStretch();
    layout->addWidget(checkoutButton);

    // 更新显示
    updateDisplay();
}

CartWidget::~CartWidget()
{
}
void CartWidget::updateDisplay()
{
    // 更新总金额显示
    double subtotal = cart->getSubtotal(); //商品价格
    double deliveryFee = cart->getDeliveryFee();//配送费
    total = cart->getTotalAmount();//总价格
//    qDebug()<<subtotal<<" "<<deliveryFee<<" "<<total;
    totalLabel->setText(QString("总金额: %1 元 (含配送费: %2 元)")
                       .arg(total, 0, 'f', 2)
                       .arg(deliveryFee, 0, 'f', 2));

    // 更新确认购买按钮状态
    checkoutButton->setEnabled(!cart->isEmpty());
}

void CartWidget::onCartChanged()
{
    updateDisplay();
}
void CartWidget::setPhoneId(int phone_id){
    this->phoneId = phone_id;
}
void CartWidget::onCheckoutClicked()
{
    // 下单前校验商家营业状态
    int businessId = cart->getBusinessId();
    int businessStatus = 1;
    if (businessId > 0) {
        QString statusSql = QString("SELECT status FROM business WHERE business_id = %1").arg(businessId);
        QSqlQuery statusQuery = db.exec(statusSql);
        if (statusQuery.next()) {
            businessStatus = statusQuery.value(0).toInt();
        }
    }
    if (businessStatus == 0) {
        QMessageBox::warning(this, "提示", "该商家正在休息，暂不可下单！");
        return;
    }
    // 这里可以实现购买功能，目前只显示消息框
    if(phoneId<0){
        QMessageBox::information(this, "提示", "还未登录！");
        //跳转到登录页
        return;
    }
    QString sql = QString("select user_id,user_money from user where phone_id = %1").arg(phoneId);

    QSqlQuery query = db.exec(sql,"cart 178-查询用户id和余额");
    query.next();
    int user_id = query.value(0).toInt();
    double user_money = query.value(1).toDouble();
//    qDebug()<<"177:"<<sql<<" "<<user_money;
    QString infor = NULL;

    // 检查用户余额是否足够支付订单
    if (user_money < total) {
        infor = "你目前的钱包余额不足以支付订单，请先充值。\n";
    }

    sql = QString("select address from address where user_id =  %1 ").arg(user_id);
//    qDebug()<<"180:"<<sql;
    query = db.exec(sql,"cart 192-查询用户地址");
    int res;
    QString userAddress = "";
    
    // 检查是否有地址
    bool hasAddress = false;
    
    while(query.next()){
        hasAddress = true;
        userAddress = query.value(0).toString();
        qDebug()<<"地址判断情况:"<<(userAddress == NULL)<<": "<<userAddress;
        if(userAddress == NULL || userAddress.isEmpty()){
            qDebug()<<"address为空";
            infor += "你目前没有添加有效的地址信息\n";
            hasAddress = false;
            break;
        }
    }
    // 如果没有地址记录或地址为空
    if (!hasAddress) {
        infor += "你目前没有添加有效的地址信息\n";
    }
    
    // 如果有足够的余额且有有效地址，则处理订单
    if (user_money >= total && hasAddress && !userAddress.isEmpty()) {
        //一切正常
        user_money = user_money-total;
//            qDebug()<<"正常 u:"<<user_money<<" t:"<<total;

        // 获取当前时间
        QDateTime currentTime = QDateTime::currentDateTime();
        QString timeStr = currentTime.toString("yyyy-MM-dd hh:mm:ss");

        // 插入订单到数据库
        bool orderSuccess = true;
        QMap<int, UserCart::CartItem> cartItems = cart->getItems();

        // 开始事务，确保所有操作都成功或都失败
        db.getDb().transaction();

        try {
            // 遍历购物车中的每个商品，生成订单
            for (auto it = cartItems.begin(); it != cartItems.end(); ++it) {
                const UserCart::CartItem &item = it.value();
                int productId = item.productId;
                int quantity = item.quantity;

                // 为每种商品创建一条订单记录，使用quantity字段记录数量
            sql = QString("INSERT INTO order_c (com_id, user_id, address, business_id, time_start, cs_id, quantity,total_price) "
                         "VALUES (%1, %2, '%3', %4, '%5', 4, %6,%7)")
                         .arg(productId)
                         .arg(user_id)
                         .arg(userAddress)
                         .arg(cart->getBusinessId())
                         .arg(timeStr)
                         .arg(quantity).arg(total);

                qDebug() << "插入订单SQL: " << sql;
                if (!db.exec(sql,"249-插入订单").isActive()) {
                    qDebug() << "插入订单失败: " << db.getDb().lastError().text();
                    orderSuccess = false;
                    break;
                }
            }
            // 更新用户余额
            if (orderSuccess) {
                sql = QString("UPDATE user SET user_money = %1 WHERE user_id = %2")
                             .arg(user_money)
                             .arg(user_id);

                qDebug() << "更新用户余额SQL: " << sql;
                if (!db.exec(sql).isActive()) {
                    qDebug() << "更新用户余额失败: " << db.getDb().lastError().text();
                    orderSuccess = false;
                }
            }
            // 如果所有操作都成功，提交事务
            if (orderSuccess) {
                db.getDb().commit();
                QMessageBox::information(this, "订单提示", "订单创建成功！");
                cart->clear(); // 清空购物车
            } else {
                // 如果有任何失败，回滚事务
                db.getDb().rollback();
                QMessageBox::warning(this, "订单提示", "订单创建失败，请稍后重试。");
            }
        } catch (const std::exception &e) {
            db.getDb().rollback();
            qDebug() << "订单处理异常: " << e.what();
            QMessageBox::warning(this, "订单提示", "订单处理出现异常，请稍后重试。");
        }
    }
    
    qDebug()<<infor;
    if(infor != NULL && !infor.isEmpty()){
        infor += "是否去添加这些信息?";
        qDebug()<<infor;
        res = QMessageBox::information(this, "提示", infor,QMessageBox::Ok|QMessageBox::No,QMessageBox::No);
        if(res == QMessageBox::Ok){
            // 发出信号，通知需要打开个人信息页面
            emit openProfilePage();

            // 用户从个人信息页面返回后，重新检查用户余额
            sql = QString("select user_money from user where phone_id = %1").arg(phoneId);
            query = db.exec(sql);
            if (query.next()) {
                double updated_money = query.value(0).toDouble();
                // 如果余额足够且有地址，可以继续下单
                if (updated_money >= total) {
                    QMessageBox::information(this, "提示", "钱包余额已更新，可以继续下单。");
                }
            }
        }
    }
}
